﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NAccounting.Models;
using AutoMapper;
using System.Data;

namespace NAccounting.Controllers
{
    public class AppointmentController : Controller
    {
        private NAccountEntities db = new NAccountEntities();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            if (Request.QueryString["Project"] == null)
                return HttpNotFound("Project number not found");

            var projectId = 0;

            if (!Int32.TryParse(Request.QueryString["Project"], out projectId))
                return HttpNotFound("Invalid project number");

            var project = db.Projects.SingleOrDefault(x => x.Id == projectId);

            if (project == null)
                return HttpNotFound("Project not found");

            var activityId = 0;

            Int32.TryParse(Request.QueryString["Activity"], out activityId);

            var model = new AppointmentDetailModel
            {
                Date = DateTime.Now.ToString("MM/dd/yyyy"),
                Project = project.Name,
                Activities = new SelectList(project.ProjectActivities, "Id", "Name", activityId)
            };

            return View("Edit", model);
        }

        [HttpPost]
        public ActionResult Create(AppointmentDetailModel model)
        {
            var entity = Mapper.Map<AppointmentDetailModel, Appointment>(model);

            db.Appointments.Attach(entity);
            db.ObjectStateManager.ChangeObjectState(entity, entity.Id > 0 ? EntityState.Modified : EntityState.Added);

            db.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id)
        {
            db.ContextOptions.LazyLoadingEnabled = false;
            var entity = db.Appointments.SingleOrDefault(x => x.Id == id);
            db.LoadProperty<Appointment>(entity, o => o.ProjectActivity);
            db.LoadProperty<ProjectActivity>(entity.ProjectActivity, o => o.Project);

            if (entity == null)
                return HttpNotFound("Appointment not found");

            var model = Mapper.Map<Appointment, AppointmentDetailModel>(entity);
            model.Activities = new SelectList(entity.ProjectActivity.Project.ProjectActivities.ToArray(), "Id", "Description");

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(AppointmentDetailModel model)
        {
            return Create(model);
        }

        public JsonResult GetAppointmentsByDate(string date)
        {
            var convertedDate = Convert.ToDateTime(date);

            var appoinments = db.Appointments.ToArray();

            var result = (from a in appoinments
                          select new { id = a.Id, title = a.Description, start = a.StartMoment.ToFullCalendarString(), end = a.EndMoment.ToFullCalendarString(), allDay = false });

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetAppointmentsByRangeDate()
        {
            var startUnixTimeStamp = 0.0;
            var endUnixTimeStamp = 0.0;

            Double.TryParse(Request.QueryString["start"], out startUnixTimeStamp);
            Double.TryParse(Request.QueryString["end"], out endUnixTimeStamp);

            var startDate = startUnixTimeStamp.ConvertFromUnixTimeStamp();
            var endDate = endUnixTimeStamp.ConvertFromUnixTimeStamp();

            var appoinments = db.Appointments.Where(x => x.Date >= startDate && x.Date <= endDate).ToArray();

            var result = (from a in appoinments
                          select new
                          {
                              id = a.Id,
                              title = a.Description,
                              start = a.StartMoment.ToFullCalendarString(),
                              end = a.EndMoment.ToFullCalendarString(),
                              allDay = false,
                              url = Url.Action("Edit", new { Id = a.Id })
                          });

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }

    public static class currentextensions
    {
        public static string ToFullCalendarString(this DateTime source)
        {
            return source.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string ToFullCalendarString(this DateTime? source)
        {
            return source.HasValue ? source.Value.ToFullCalendarString() : "";
        }
    }
}
